#!/bin/bash

ARG_COUNT=$#  #参数的个数
BUILD_DIR="build"
CACHE_FILE="${BUILD_DIR}/CMakeCache.txt"

# 确保构建目录存在
mkdir -p $BUILD_DIR
cd $BUILD_DIR
# 检查传入的参数是否为 "test" 或 "src"
if [ "$1" == "test" ]; then
    BUILD_TESTS=ON
    BUILD_SRC=OFF
elif [ "$1" == "src" ]; then
    BUILD_TESTS=OFF
    BUILD_SRC=ON
else
    echo "Usage: $0 {test|src}"
    exit 1
fi

# 检查 CMake 配置是否需要更新
if [ ! -f "$CACHE_FILE" ] || ! grep -q "BUILD_TESTS=${BUILD_TESTS}" "$CACHE_FILE" || ! grep -q "BUILD_SRC=${BUILD_SRC}" "$CACHE_FILE"; then
    echo "Configuring project with CMake..."
    rm -rf $BUILD_DIR/*  # 清理之前的构建文件
    cmake .. -DBUILD_TESTS=$BUILD_TESTS -DBUILD_SRC=$BUILD_SRC -DCMAKE_TOOLCHAIN_FILE=toolchain.cmake
    if [ $? -ne 0 ]; then
        echo "CMake configuration failed"
        exit 1
    fi
else
    echo "Skipping CMake configuration as cache is up-to-date."
fi

# 执行构建
echo "Building the project..."
make

# 检查构建是否成功
if [ $? -ne 0 ]; then
    echo "Build failed"
    exit 1
fi
